
from takeaway import resp
from takeaway.store import user as user_store


def get_addresses(user_id):
    addresses = [
        dict(id=address.id, name=address.name, phone=address.phone, place=address.place)
        for address in user_store.select_addresses(user_id)
    ]

    return resp.make_success(data=addresses)


def add_address(user_id, address_name, address_phone, address_place):
    a = user_store.insert_address(user_id, address_name, address_phone, address_place)
    return resp.make_success(data=dict(id=a.id, name=a.name, phone=a.phone, place=a.place))


def select_address(user_id, address_id):
    return user_store.select_address(user_id, address_id)


def update_address(user_id, address_id, **kwargs):
    address = select_address(user_id, address_id)
    if not address:
        return resp.make_fail(msg="invalid address")

    address = user_store.update_address(address, **kwargs)
    return resp.make_success(data=dict(id=address.id, name=address.name, phone=address.phone,place=address.place))
